package org.snusmumr.android.media;

import java.util.Formatter;

import org.snusmumr.android.media.bean.LabelModel;
import org.snusmumr.android.media.data.DatabaseProvider;
import org.snusmumr.android.media.data.DatabaseProvider.DatabaseMode;
import org.snusmumr.android.media.data.adapter.LabelCursorAdapter;
import org.snusmumr.android.media.dialog.LabelDialog;
import org.snusmumr.android.media.dialog.LabelDialog.OnSaveItemListener;
import org.snusmumr.android.media.util.Utils;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class LabelTab extends ListActivity {
	private LabelDialog labelDlg;
	private ListView labelsView;
	private DatabaseProvider dbProvider;
	private CursorAdapter adapter;
	
	private OnItemClickListener itemClickedHandler = new OnItemClickListener() {
	    public void onItemClick(AdapterView<?> parent, View v, int position, long id)
	    {
	    	Cursor c = (Cursor) adapter.getItem(position);
			String listItemName = c.getString(1);
	        
	        Intent intent = new Intent(LabelTab.this, MediaList.class);
	        intent.putExtra(Constants.KEY_PARENT_ID, id);
	        intent.putExtra(Constants.KEY_PARENT_NAME, listItemName);
	        intent.putExtra(Constants.KEY_PARENT_TYPE, MediaList.ParentType.Labels);
			startActivity(intent);
	    	
	    	
//			Cursor c = (Cursor) adapter.getItem(position);
//			String listItemName = c.getString(1);
//			
//	        Toast.makeText(LabelTab.this,"Item " + listItemName + " clicked. ID=" + id,Toast.LENGTH_SHORT).show();
	    }
	};
	
	private OnSaveItemListener labelChangedListener = new OnSaveItemListener() {
		@Override
		public void onLabelChanged(Long labelID, String label, int color) {
			if(labelID == null)
				addItem(label, color);
			else
				updateItem(labelID, label, color);
		}
	};
	
//	@Override
//	protected void onListItemClick(ListView l, View v, int position, long id) {
//		super.onListItemClick(l, v, position, id);
//		
//		Cursor c = (Cursor) adapter.getItem(position);
//		String listItemName = c.getString(1);
//        
//        Intent intent = new Intent(LabelTab.this, MediaList.class);
//        intent.putExtra(Constants.KEY_PARENT_ID, id);
//        intent.putExtra(Constants.KEY_PARENT_NAME, listItemName);
//        intent.putExtra(Constants.KEY_PARENT_TYPE, MediaList.ParentType.Labels);
//		startActivity(intent);
//	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		labelsView = new ListView(this);
        labelsView.setId(android.R.id.list);
        setContentView(labelsView);
        
        dbProvider = DatabaseProvider.getInstance(this);
        
		labelsView.setOnItemClickListener(itemClickedHandler);
		registerForContextMenu(labelsView);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		Utils.closeCursor(adapter);
		dbProvider.close();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		loadData();
	}

	private void loadData() {
		Cursor cursor = dbProvider.getDatabase(DatabaseMode.Read).query(Constants.DB_TABLE_LABEL, 
				Constants.DB_COLUMNS_LABEL, 
				null, null, null, null, "name asc");
		startManagingCursor(cursor);
		
		adapter = new LabelCursorAdapter(this, cursor);
		setListAdapter(adapter);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.label_tab_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.mn_label_add:
			showAddLabelDlg();
			return true;
		case R.id.mn_settings:
			Toast.makeText(this, "settings selected", Toast.LENGTH_SHORT).show();
			return true;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		if(v == labelsView) {
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.items_context, menu);
			
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
			Cursor c = (Cursor) adapter.getItem(info.position);
		    menu.setHeaderTitle(c.getString(1));
		}
		super.onCreateContextMenu(menu, v, menuInfo);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
		Cursor c = (Cursor) adapter.getItem(info.position);
		String listItemName = c.getString(1);
		final long id = c.getLong(0);
		final int color = c.getInt(2);
		
		switch (item.getItemId()) {
		case R.id.men_item_delete:
			Resources res = getResources();
			final Formatter format = new Formatter();
			String message = format.format(res.getString(R.string.msg_sure_to_delete), listItemName).toString();
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(message).setCancelable(false)
			.setPositiveButton(android.R.string.yes, new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					deleteItem(id);
				}
			}).setNegativeButton(android.R.string.no, new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			}).show();
			return true;
		case R.id.men_item_edit:
			new LabelDialog(this, new LabelModel(id, listItemName, color), labelChangedListener).show();
			return true;
		default:
			break;
		}
		return super.onContextItemSelected(item);
	}
	
	private void showAddLabelDlg() {
		if(labelDlg == null) {
			labelDlg = new LabelDialog(this, null, labelChangedListener);
			
		} else {
			EditText et = (EditText) labelDlg.findViewById(R.id.et_label_item);
			et.setText("");
		}
		
		labelDlg.show();
	}

	public void addItem(String name, int color) {
		if(name != null && name.length() > 0) {
			ContentValues values = new ContentValues();
			values.put("name", name);
			values.put("color", color);
			dbProvider.getDatabase(DatabaseMode.Write).insert(Constants.DB_TABLE_LABEL, null, values);
			loadData();
		}
	}
	
	public void updateItem(Long id, String name, int color) {
		if(id != null && name != null && name.length() > 0) {
			ContentValues values = new ContentValues();
			values.put("name", name);
			values.put("color", color);
			dbProvider.getDatabase(DatabaseMode.Write).update(Constants.DB_TABLE_LABEL, values, "_id=?", new String[]{String.valueOf(id)});
			loadData();
		}
	}
	
	public void deleteItem(Long id) {
		if(id != null) {
			dbProvider.getDatabase(DatabaseMode.Write).delete(Constants.DB_TABLE_LABEL, "_id=?", new String[]{String.valueOf(id)});
			loadData();
		}
	}
}
